#!/usr/bin/ruby

require 'cgi'
require "sqlite3"
require 'pp'

#require File.dirname(__FILE__) + "/shared.rb"
require '/opt/radio-monitor/shared.rb'
require FORM_RB
require CONFIRM_RB
require JOIN_RB

FORM_CGI_VARS = ["start_year", "start_month", "start_day", \
"start_hour", "start_min", "same_day", "end_hour", "end_min"]
CONFIRM_CGI_VAR = "confirmed"

if __FILE__ == $0
    
    cgi = CGI.new.params

    if not FORM_CGI_VARS.map {|v| cgi.member?(v)}.member?(false)
        puts "Content-type: text/html \n\n"
        puts "<!-- #{cgi} -->"

        start_year  = cgi["start_year"][0].to_i
        start_month = cgi["start_month"][0]
        start_day   = cgi["start_day"][0]
        start_hour  = cgi["start_hour"][0]
        start_min   = cgi["start_min"][0]
        end_day     = start_day
        end_hour    = cgi["end_hour"][0]
        end_min     = cgi["end_min"][0]

        req_start_t = Time.mktime(\
            start_year, start_month, start_day, start_hour, start_min).to_i
        req_end_t = Time.mktime(\
            start_year, start_month, start_day, end_hour, end_min).to_i
        req_end_t += 24*60*60   if cgi["same_day"][0] == "False"

        db = SQLite3::Database.new(DB_FILE)
        l = db.execute("SELECT * FROM Recordings WHERE \
            #{req_start_t} <= start_t and start_t < #{req_end_t} \
            and have_file == 1")

        print_confirm(l)
    elsif cgi.member?(CONFIRM_CGI_VAR)
        puts "Content-type: application/ogg\n\n"
        start_t_list = cgi[CONFIRM_CGI_VAR].map {|x| x.to_i}
        #pp start_t_list
        join_recs(start_t_list)
    else
        puts "Content-type: text/html \n\n"
        puts "<!-- #{cgi} -->"
        print_form()
    end

end

